<?php

/*
 * CopyRight  : (C)2012-2099 HaoTeam Inc.
 * Document   : Std3desService.php
 * Created on : 2023-4-14 10:20:31
 * Author     : Tiger <1192851302@qq.com>
 * Description: This is NOT a freeware, use is subject to license terms.
 *              这即使是一个免费软件,使用时也请遵守许可证条款,得到当时人书面许可.
 *              未经书面许可,不得翻版,翻版必究;版权归属 HaoTeam Inc;
 */

namespace haoteam\service;

/**
 * 
 * Class Std3desService
 * Tiger <1192851302@qq.com> 2023-4-14 10:20:31
 */
class Std3desService {

    /**
     * 数据加密
     * @author Tiger <1192851302@qq.com>
     * @param type $str
     * @param type $key
     * @param type $function base64_encode bin2hex
     * @return type
     */
    public static function encrypt($str, $key, $function = 'base64_encode') {
        $message_padded = self::pkcs5_pad($str, 8);
        if (strlen($message_padded) % 8) {
            $message_padded = str_pad($message_padded, strlen($message_padded) + 8 - strlen($message_padded) % 8, "\0");
        }
        $encrypted_openssl = openssl_encrypt($message_padded, "DES-EDE3", $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING);
        return base64_encode($encrypted_openssl);
    }

    /**
     * 数据解密
     * @author Tiger <1192851302@qq.com>
     * @param type $encrypted
     * @param type $key
     * @param type $function hex2bin base64_decode
     * @return type
     */
    public static function decrypt($encrypted, $key, $function = 'base64_decode') {
        $data = $function($encrypted);
        $decrypted_openssl = openssl_decrypt($data, 'DES-EDE3', $key, OPENSSL_RAW_DATA);
        return $decrypted_openssl;
    }

    private static function pkcs5_pad($text, $blocksize) {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }

}
